#coding=utf-8

import sys

from pyquery import PyQuery as pq

sys.setdefaultencoding('utf8')


class HtmlProcessor(object):
    def __init__(self, tag_name):
        self._tag_name = tag_name
        self._item = None

    def processing(self, item):
        self._item = item
        if item.has_key('_htmldom'):
            doc = item['_htmldom']
        else:
            doc = pq(item['content'])
            item['_htmldom'] = doc

        tag_list = doc(self._tag_name).items()
        for tag in tag_list:
            self.processing_tag(tag)

        item['content'] = doc.html(encoding='utf-8')
        return item

    def processing_tag(self, tag):
        pass


class HtmlImageResizeProcessor(HtmlProcessor):
    def __init__(self, width=None, height=None):
        HtmlProcessor.__init__(self, 'img')
        self._width = width
        self._height = height

    def processing_tag(self, tag):
        if self._width:
            tag.removeAttr('width')
            tag.attr('width', self._width)

        if self._height:
            tag.removeAttr('height')
            tag.attr('height', self._height)


class HtmlRemoveAttributeProcessor(HtmlProcessor):
    def __init__(self, attr_list=None):
        HtmlProcessor.__init__(self, '*')
        self._attr_list = attr_list

    def processing_tag(self, tag):
        if self._attr_list:
            for attr in self._attr_list:
                tag.removeAttr(attr)


class HtmlRemoveSectionProcessor(HtmlProcessor):
    def __init__(self, tag_name):
        HtmlProcessor.__init__(self, tag_name)

    def processing_tag(self, tag):
        tag.remove()
